package com.web.filter;


import com.web.utils.CurrentHolder;
import com.web.utils.JwtUtils;
import io.jsonwebtoken.Claims;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
@CrossOrigin
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;


//        1. 获取请求url
        String url = request.getRequestURL().toString();

//        2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(url.contains("login")){
            log.info("登录请求 , 直接放行");
            filterChain.doFilter(request,response);
            return;
        }


//        3. 获取请求头中的令牌（token）
        String jwt = request.getHeader("token");
        log.info("获取到jwt令牌：{}",jwt);


//        4. 判断令牌是否存在，如果不存在，响应 401
        if(!StringUtils.hasLength(jwt)){
            log.info("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }


//        5. 解析token，如果解析失败，响应 401
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            Integer empId = Integer.valueOf(claims.get("userId").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前登录员工的id：{},将其存入ThreadLocal",empId);


        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

//        6. 放行
        log.info("令牌合法, 放行");
        filterChain.doFilter(request , response);


        //7.删除ThreadLocal的数据
        CurrentHolder.remove();
    }
}
